import { Wristband } from "@/entity/wristband.entity";
import { WristbandAdv } from "@/entity/wristband_adv.entity";
import { WristbandHistory } from "@/entity/wristband_history.entity";
import { Repository } from "typeorm";
import { v4 as uuidv4 } from 'uuid';
// 创建手环广播数据
export async function createWbHistory(
    gw_mac: string,
    mac: string,
    rssi: number,
    data: Partial<WristbandAdv>,
    format: number,
    date: Date,
    wristbandRepo: Repository<Wristband> | null,
    wristbandHistoryRepo: Repository<WristbandHistory> | null
): Promise<WristbandAdv | undefined> {
    if (wristbandRepo && wristbandHistoryRepo) {
        try {
            // 检查 wristband 是否存在
            const existingWristband = await wristbandRepo.findOne({ where: { mac } });
            if (!existingWristband) {
                // 使用 save 方法插入或更新记录
                await wristbandRepo
                    .createQueryBuilder()
                    .insert()
                    .into(Wristband)
                    .values({
                        id: uuidv4(),
                        mac,
                        // time: date,
                        time: new Date()
                    })
                    .orIgnore() // 如果 mac 地址已存在则忽略
                    .execute();
                // console.log(`Wristband checked/added with MAC: ${mac}`);
            } else {
                // console.log(`Wristband with MAC: ${mac} already exists.`);
            }

            // 插入 wristbandAdv（无条件新增）
            const newWristbandHistory = {
                gw_mac,
                mac,
                rssi,
                ...data,
                // time: date,
                time: new Date(),
                format
            };
            try {
                const savedRecord = await wristbandHistoryRepo.save(newWristbandHistory);
                // console.log(`WristbandAdv added with ID: ${savedRecord.id}`);
                return savedRecord;
            } catch (err) {
                console.log('err', err)
            }

        } catch (err: any) {
            console.error('Error occurred while creating wristbandAdv:', err.message);
            // throw new Error('Failed to create wristbandAdv record');
        }
    }

}
